﻿using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Services;
using GKQC.Language;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Configuration;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;

namespace GKQC
{
    public partial class FormUserGroup : Form
    {
        UserModel user = null;
        AllDbContext dbContext = null;
        List<UserGroupModel> userGroups = null;
        FormStatus formStatus = FormStatus.Browser;
        readonly string countText = "記錄數：{0}";

        public FormUserGroup(UserModel user, AllDbContext dbContext)
        {
            InitializeComponent();
            try
            {
                this.user = user;
                this.dbContext = dbContext;

                dataGridView1.RowPostPaint += DataGridView1_RowPostPaint;
                dataGridView1.AutoGenerateColumns = false;
                this.userGroups = new List<UserGroupModel>();
                BindData();
                SetControlsEnable();
                LanguageHelper.SetControlLanguageText(this);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message);
                Logger.LogError(ex);
            }
        }

        private void DataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewSet.RowPostPaint(sender, e);
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            if(!UserRightService.CheckRight(this,this.user,RightType.Modi))
            {
                return;
            }
            formStatus = FormStatus.Edit;
            SetControlsEnable();
        }

        private void tsmCancel_Click(object sender, EventArgs e)
        {
            formStatus = FormStatus.Browser;
            SetControlsEnable();
            BindData();
        }


        private void tsmSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                dataGridView1.EndEdit();
                List<UserGroupModel> listInsert = new List<UserGroupModel>();
                List<UserGroupModel> listUpdate = new List<UserGroupModel>();
                foreach (DataGridViewRow r in dataGridView1.Rows)
                {
                    UserGroupModel model = r.DataBoundItem as UserGroupModel;
                    if (model == null) continue;

                    string msg = string.Empty;
                    if (!ValidatingRow(model, out msg))
                    {
                        QMessageBox.Show(msg, "驗證失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    int Id = 0;
                    int.TryParse(model.Id.ToString(), out Id);
                    if (Id <0)
                    {
                        listInsert.Add(model);// dbContext.QcDb.Insertable<UserGroupModel>(model).ExecuteCommand();
                    }
                    else
                    {
                        if (model.IsModified)
                            listUpdate.Add(model);// dbContext.QcDb.Updateable<UserGroupModel>(model).ExecuteCommand();
                    }
                }

                if (listInsert.Count > 0) dbContext.QcDb.Insertable<UserGroupModel>(listInsert).ExecuteCommand();
                if(listUpdate.Count > 0) dbContext.QcDb.Updateable<UserGroupModel>(listUpdate).ExecuteCommand();

                formStatus = FormStatus.Browser;
                SetControlsEnable();
                BindData();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                if (ex.Message.Contains("pk_t_sys_usergroup"))
                    QMessageBox.Show("组别代码重复，请检查", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else QMessageBox.Show(ex.Message,"錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if(dataGridView1.SelectedRows.Count == 0)
            {
                QMessageBox.Show("請選擇要刪除的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (QMessageBox.Show("刪除後無法恢復，請確認是否刪除？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2)
                == DialogResult.No)
                return;

            int i = 0;
            foreach (DataGridViewRow r in dataGridView1.SelectedRows)
            {
                UserGroupModel model = r.DataBoundItem as UserGroupModel;
                i += dbContext.QcDb.Deleteable<UserGroupModel>(model).ExecuteCommand();
            }

            if(i>0)
            {
                QMessageBox.Show("成功刪除記錄 " + i.ToString() + " 條。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                BindData();
            }
            else
            {
                QMessageBox.Show("未刪除任何記錄", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        void SetControlsEnable()
        {
            if(formStatus == FormStatus.Browser)
            {
                tsmSave.Enabled = false;
                tsmCancel.Enabled = false;
                tsmEdit.Enabled = true;
                tsmExit.Enabled = true;
                tsmDelete.Enabled = true;
                dataGridView1.ReadOnly = true;
            }
            else
            {
                tsmSave.Enabled = true;
                tsmCancel.Enabled = true;
                tsmEdit.Enabled = false;
                tsmExit.Enabled = false;
                tsmDelete.Enabled = false;
                dataGridView1.ReadOnly = false;
            }
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            UserGroupModel model = dataGridView1.Rows[e.RowIndex].DataBoundItem as UserGroupModel;
            DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
            if (model != null)
            {
                int Id = 0;
                int.TryParse(model.Id.ToString(), out Id);
                if(Id >0 && column.DataPropertyName == "GroupCode")
                {
                    e.Cancel = true;
                    return;
                }

                model.IsModified = true;
            }
        }

        void BindData()
        {
            dataGridView1.EndEdit();

            var rs = this.dbContext.QcDb.Queryable<UserGroupModel>();
            if (rs != null && rs.Count() > 0) this.userGroups = rs.ToList();
            else this.userGroups.Clear();

            if (userGroups.Count > 0) userGroups.ForEach(t => t.Id = 1);
            dataGridView1.DataSource = new BindingList<UserGroupModel>(userGroups);
            toolStripStatusLabel1.Text = string.Format(countText, this.userGroups.Count.ToString());
        }

        bool ValidatingRow(UserGroupModel model,out string msg)
        {
            bool flag = true;
            msg = string.Empty;

            if (model == null) throw new ArgumentException("模型參數為空！");

            if(string.IsNullOrWhiteSpace(model.GroupCode))
            {
                msg = "代號不能為空";
                return false;
            }

            //int Id = 0;
            //int.TryParse(model.Id.ToString(),out Id);
            //if(Id<=0)
            //{
            //    UserGroupModel m = dbContext.QcDb.Queryable<UserGroupModel>().Where(p => p.GroupCode == model.GroupCode).Single();
            //    if(m!=null)
            //    {
            //        msg = "代號重複：" + model.GroupCode;
            //        return false;
            //    }
            //}

            return flag;
        }

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (formStatus == FormStatus.Browser) return;

            if(dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "GroupCode")
            {
                string code = e.FormattedValue.ToString().ToLower();
                foreach(DataGridViewRow r in dataGridView1.Rows)
                {
                    if (r == dataGridView1.Rows[e.RowIndex]) continue;
                    if (r.Cells["ColGroupCode"].Value == null) continue;

                    if(r.Cells["ColGroupCode"].Value.ToString().ToLower()== code)
                    {
                        e.Cancel = true;
                        QMessageBox.Show("代號重複：" + r.Cells["ColGroupCode"].Value.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            BindData();
        }
    }
}
